package org.leiyang.controller;

import org.leiyang.common.dtos.R;
import org.leiyang.common.entities.MsgOneToOne;
import org.leiyang.common.redis.ReactiveRedisCache;
import org.leiyang.common.dtos.MsgDTO;
import org.leiyang.domain.dtos.MsgReceiveResp;
import org.leiyang.service.OfflineMessageService;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

import static org.leiyang.common.util.Constants.*;
import static org.leiyang.mq.NewMsgConsumer.topicName;

/**
 * 聊天服务里用于发起聊天的应用层
 */
@RestController
@RequestMapping("/talk")
public class TalkMsgController {

    private final ReactiveRedisCache redisCache;
    private final OfflineMessageService offlineMessageService;
    public TalkMsgController(ReactiveRedisCache redisCache, OfflineMessageService offlineMessageService) {
        this.redisCache = redisCache;
        this.offlineMessageService = offlineMessageService;
    }

    /**
     * 供客户端发送单聊消息
     * @param msg 单聊消息
     * @return 发送是否成功
     */
    @PostMapping("/msgSend")
    public Mono<R<String>> MsgOneToOneSend(@RequestHeader(DETAILS_USER_ID) String uid, @RequestBody MsgOneToOne msg) {
        //重新设置消息发送者ID
        msg.setFromUserId(Long.parseLong(uid));
        return redisCache.createStreamOperations().add(topicName, MsgOneToOne.convertToMap(msg))
                .map(recordId -> R.ok());
    }

    /**
     * 供客户端发送消息接收成功的通知
     */
    @PostMapping("/msgs/reve/notice")
    public Mono<R<String>> MsgsReceiveSuccess(@RequestBody MsgReceiveResp req) {
        return redisCache.createStreamOperations().add(MSG_REC_SUCCESS_TOPIC, MsgReceiveResp.convertToMap(req))
                .map(recordId -> R.ok());
    }

    /**
     * 向聊天服务发送上线请求
     * 客户端在自己的token校验通过之后调用该接口
     * @param uid 用户ID
     * @param clientIp 客户端出口公网IP
     */
    @PostMapping("/login/notice")
    public Mono<R<Boolean>> UserLoginNotice(@RequestHeader(DETAILS_USER_ID) String uid, @RequestHeader(CLIENT_IP) String clientIp) {
        return offlineMessageService.offlineMsgsSendWhenLogin(Long.parseLong(uid), clientIp)
                .map(send -> send ? R.ok(true) : R.fail(false));
    }

    /**
     * 查询当前用户与用户A的聊天记录
     * 待改为分页查询方式
     */
    @GetMapping("/history/msgs")
    public Mono<R<List<MsgDTO>>> listAllHistoryMsgs(@RequestHeader(DETAILS_USER_ID) String uid, Long toUid, Integer currentPage) {
        return offlineMessageService.listAllHistoryMsgs(Long.parseLong(uid), toUid, currentPage);
    }


}
